const { isAndroid, isIOS } = getBrowerInfo()

function getBrowerInfo() {
  const ua = window.navigator.userAgent.toLowerCase()
  const isAndroid = /Android/i.test(ua)
  const isIOS = /iPhone|iPad|iPod/i.test(ua)
  return { isIOS, isAndroid }
}

function isJSON(str) {
  if (typeof str === 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
  return false
}

function connectIOSBridge(callback) {
  if (window.WebViewJavascriptBridge) return callback(window.WebViewJavascriptBridge)
  if (window.WVJBCallbacks) return window.WVJBCallbacks.push(callback)
  window.WVJBCallbacks = [callback]
  const WVJBIframe = document.createElement('iframe')
  WVJBIframe.style.display = 'none'
  WVJBIframe.src = 'jkbp://__BRIDGE_LOADED__'
  document.documentElement.appendChild(WVJBIframe)
  setTimeout(() => { document.documentElement.removeChild(WVJBIframe) }, 0)
}

function connectAndroidBridge(callback) {
  if (window.WebViewJavascriptBridge) {
    callback(window.WebViewJavascriptBridge)
  } else {
    document.addEventListener('WebViewJavascriptBridgeReady', function() {
      callback(window.WebViewJavascriptBridge)
    }, false)
  }
}

/**
 * 函数描述：js注册方法给app调用
 *
 * jsBridge.registerHandler(name, callback(data, appCallback))
 * @param {String} name 方法名
 * @param {Function} callback 回调函数
 * @param {Any} callback.data app返回的数据
 * @param {Function} callback.appCallback app返回的回调
 * @return
 */
function registerHandler(name, callback) {
  const connectBridge = (bridge) => {
    bridge.registerHandler(name, (data, appCallback) => {
      if (isJSON(data)) data = JSON.parse(data)
      if (typeof callback === 'function') callback(data, appCallback)
    })
    bridge.registerHandler(name, callback)
  }
  if (isIOS) {
    connectIOSBridge(connectBridge)
  } else if (isAndroid) {
    connectAndroidBridge(connectBridge)
  }
}

/**
 * 函数描述：js调用app方法
 *
 * jsBridge.callHandler(name, params, callback)
 * @param {String} name 方法名
 * @param {Object} params 参数
 * @param {Function} callback 回调函数
 * @return
 */
function callHandler(name, params, callback) {
  const connectBridge = (bridge) => {
    bridge.callHandler(name, params, (data) => {
      if (isJSON(data)) data = JSON.parse(data)
      if (typeof callback === 'function') callback(data)
    })
  }
  if (isIOS) {
    connectIOSBridge(connectBridge)
  } else if (isAndroid) {
    connectAndroidBridge(connectBridge)
  }
}

function onInit() {
  if (isAndroid) {
    connectAndroidBridge((bridge) => {
      bridge.init()
    })
  }
}
onInit()

const JsBridge = {
  registerHandler,
  callHandler
}
window.JsBridge = JsBridge
export default JsBridge
